<?php

class WxNewAction extends CommonAction
{
	public function index(){
		$model = M();

		$sql = 'SELECT COUNT(DISTINCT id) AS tcount FROM '.C("DB_PREFIX")."wx_new_item WHERE title !=''";
		
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX")."wx_new_item WHERE title !=''";
			
		$this->_sqlList($model,$sql,$count,$parameter,'id');
		
		$this->display ();
		return;
	}
	
	public function update(){
		$type = 'news';
		$offset = isset($_GET['offset'])?$_GET['offset']:0;
		$count = 20;
		$access_token = get_token();
		$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token;  
		$data = '{"type":"'.$type.'","offset":"'.$offset.'","count":"'.$count.'"}';  
		
		//返回的数据  
		$response = get_response_post($url, $data);  
		//echo strip_tags($response);  
		$res = json_decode($response, true);  
		//var_dump($res['item'][0]); exit;
		foreach($res['item'] as $k=>$v){
			
			$media_id = $v['media_id'];
			$create_time = $v['update_time'];
			$list = D('WxNew')->where("media_id='".$media_id."'")->select();
			if(count($list)<=0){
				$sql = "insert into tbl_wx_new (create_time,media_id,status) values({$create_time},'{$media_id}',1)";
			
				D('WxNew')->query($sql);
				$pid = mysql_insert_id();
				foreach($v['content']['news_item'] as $key=>$val){
					$title = $val['title'];
					$author = $val['author'];
					$grid = $val['digest'];
					$thumb_media_id = $val['thumb_media_id'];
					$show_cover_pic = $val['show_cover_pic'];
					$url = $val['url'];
					$thumb_url = $val['thumb_url'];
					$local_img = '';
					$img_data = @file_get_contents($thumb_url);
					if(!empty($img_data)){
						$dtime = date('md');
						
						$dir = '/server/www/res/public/upload/news/'.$dtime.'/';
						
						if(!file_exists($dir)){
							
							mkdir('/server/www/res/public/upload/news/'.$dtime.'/');
						}
						$pdir = '/server/www/res/';
						$img_index = 'public/upload/news/'.$dtime.'/'.$thumb_media_id.'.jpg';
						
						$img_size = @file_put_contents($pdir.$img_index, $img_data);
						$local_img = $img_index; 
					}      					 
					
					$item_sql = "insert into tbl_wx_new_item (title,author,thumb_media_id,show_cover_pic,url,thumb_url,pid,sort,grid,local_img,status) 
					values('".$title."','".$author."','".$thumb_media_id."',".$show_cover_pic.",'".$url."','".$thumb_url."',".$pid.",".$key.",'".$grid."','".$local_img."',1)";
					mysql_query($item_sql);
				}
			}else{
				$this->redirect('WxNew/index');
			}
			
		}
		$oset = $offset+20;
		if($oset<6458){
			header('Location:http://www.zaijiahome.com/trends/index.php?m=WxNew&a=update&offset='.$oset);
		}else{
			$this->redirect('WxNew/index');
		}
		
	}
	
	public function remove()
	{
		//删除指定记录
		$result = array('isErr'=>0,'content'=>'');
		$id = $_REQUEST['id'];

		if(!empty($id))
		{
			$name=$this->getActionName();
			$model = D($name);
			$pk = $model->getPk ();
			
			if(D("Album")->where(array("cid"=>array('in',explode(',',$id))))->count()>0)
			{
				$result['isErr'] = 1;
				$result['content'] = L('ALBUM_EXIST');
				die(json_encode($result));
			}
			
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
			$datas = $model->where($condition )->field('best_img')->findAll();
			if(false !== $model->where ( $condition )->delete ())
			{
				foreach($datas as $data)
				{
					if(!empty($data['best_img']))
						@unlink(RES_ROOT.$data['best_img']);
					
				}
				$this->saveLog(1,$id);
			}
			else
			{
				$this->saveLog(0,$id);
				$result['isErr'] = 1;
				$result['content'] = L('REMOVE_ERROR');
			}
		}
		else
		{
			$result['isErr'] = 1;
			$result['content'] = L('ACCESS_DENIED');
		}
		
		die(json_encode($result));
	}
}

 
function get_token() {  
	$appid = 'wxbcb9db2f64155de8';
	$secret = '64dc86abe049f26e0656158c39d8eb4e';
	
	$data = D("Token")->find();
	if(count($data)>0){
		$token = $data['tk'];
		$ctime = $data['create_time'];	
		if ($ctime<time()) {
			$token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
			$access_token = json_decode(file_get_contents($token_url));
			if (isset($access_token->errcode)) {
				echo '<h1>错误：</h1>'.$access_token->errcode;
				echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
				exit;
			}
			$token = $access_token->access_token;
			$time = time()+3600;
			$tsql = "update tbl_token set tk='".$token."',create_time=".$time;
			D("Token")->query($tsql);
			
		}
	}else{
		$token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
		$access_token = json_decode(file_get_contents($token_url));
		if (isset($access_token->errcode)) {
			echo '<h1>错误：</h1>'.$access_token->errcode;
			echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
			exit;
		}
		$token = $access_token->access_token;
		$time = time()+3600;
		$tsql = "insert into tbl_token (tk,create_time) values('".$token."',".$time.")";
		D("Token")->query($tsql);
	}
	
  return $token;  
}
  
function get_response_post($url, $data)  
{  
	 $params = array('http' => array(
                 'method' => 'POST',
                 'content' => $data
              ));
    if ($optional_headers !== null) {
       $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
       throw new Exception("Problem with $url, $php_errormsg");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
       throw new Exception("Problem reading data from $url, $php_errormsg");
    }
    return $response;
} 
?>